#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@author: lyndon
@time Created on 2018/12/10 16:10
@desc
"""
from os import sep
from flask import Response

from analyzer.bin import app
from analyzer.conf.settings import est, imgdir
from analyzer.core.jiebacloudcore import JiebaCloud


@app.route('/HelloWorld', methods=['GET'])
def hello_world():
    return "Hello World!"


@app.route("/image/<phone_no>", methods=['GET'])
def get_image(phone_no):
    imgPathCfg = imgdir + sep + phone_no + '.png'
    # 先根据手机号码，拿到所有上微信公众号的article_id
    body = {
        "size": 200,
        "query": {
            "match_phrase": {
                "msisdn": phone_no
            }
        }
    }
    phone_columns = ['article_id']
    article_ids = est.getattr_bybodyattr(index='tb_phone_url', doc_type='_doc', body=body, columns=phone_columns)
    # print(ret)
    content_columns = ['content']
    content_list = []
    for i in article_ids:
        aid = i['article_id']
        # print(aid)
        content = est.getattr_byattr('tb_library', '_doc', aid, content_columns)
        content_list.append(content)

    jiebacld = JiebaCloud("man.jpg", imgdir)
    text1 = jiebacld.jiebaclearText(content_list)

    if text1 is not None and text1 != '':
        imgPathCfg = jiebacld.gen_img(imgPathCfg, text1)
    else:
        imgPathCfg = imgdir + sep + 'man.jpg'

    # imgPath = imgPathCfg.format(uri)
    mdict = {
        'jpeg': 'image/jpeg',
        'jpg': 'image/jpeg',
        'png': 'image/png',
        'gif': 'image/gif'
    }
    mime = mdict[imgPathCfg.split(sep)[-1].split('.')[1]]
    # if not os.path.exists(imgPath):
    #     # Res 是我自己定义的返回类，raw方法将数据组成字典返回
    #     return jsonify(Res(0, 'image does not exists').raw())
    with open(imgPathCfg, 'rb') as f:
        image = f.read()
    return Response(image, mimetype=mime)


if __name__ == "__main__":
    # 这种是不太推荐的启动方式，我这只是做演示用，官方启动方式参见：http://flask.pocoo.org/docs/0.12/quickstart/#a-minimal-application
    app.run(debug=True)
